/*global pi */
pi.mod.define('pi.scene.camsys', function (pi) {
	"use strict";

	var module = {};

	/** 创建第三人称摄像机 */
	module.createThirdPerson = function (cam) {
		var sys = {},
			obj, // 跟随目标
			offset = {x: 0, y: 0, z: 0}, // 跟随点距离目标的偏移
			aimOldPos, // 跟随目标上一次位置
			dist = 0, // 摄像机与目标距离
			yaw = 0, // 偏角
			pitch = 0, // 仰角
			dirty = false; // 是否变动了参数

		/** 获取摄像机对象 */
		sys.getCamera = function () {
			return cam;
		};

		/** 获取摄像机距离目标的距离 */
		sys.getDistance = function () {
			return dist;
		};

		/** 跟随目标 */
		sys.setAim = function (aim) {
			obj = aim;
			dirty = true;
		};

		/** 转动摄像机 */
		sys.rotate = function (r) {
			yaw += r;
			dirty = true;
		};

		/** 拉升摄像机 */
		sys.pullup = function (r) {
			pitch += r;
			dirty = true;
		};

		/** 推进或拉远摄像机 */
		sys.push = function (d) {
			dist += d;
			dirty = true;
		};

		/** 设置偏角、仰角、距离等参数 */
		sys.setParams = function (params) {
			yaw = params.yaw || yaw;
			pitch = params.pitch || pitch;
			dist = params.dist || dist;
			offset = params.offset || {x: 0, y: 0, z: 0};
			dirty = true;
		};

		/** 获取当前摄像机方向 */
		sys.getDir = function () {
			return {
				x: -Math.cos(yaw + Math.PI / 2),
				y: -Math.sin(pitch),
				z: -Math.sin(yaw + Math.PI / 2)
			};
		};

		/** 更新摄像机 */
		sys.update = function (timeElapsed) {
			var aimPos = obj.getPos(),
				camPos = {};

			if (!dirty
					&& aimOldPos !== undefined
					&& aimOldPos.x === aimPos.x
					&& aimOldPos.y === aimPos.y
					&& aimOldPos.z === aimPos.z) {
				return;
			}

			camPos.x = aimPos.x + offset.x + dist * Math.cos(yaw + Math.PI / 2);
			camPos.z = aimPos.z + offset.z + dist * Math.sin(yaw + Math.PI / 2);
			camPos.y = aimPos.y + offset.y + dist * Math.sin(pitch);

			cam.setPos(camPos);
			cam.lookAt({x: aimPos.x + offset.x, y: aimPos.y + offset.y, z: aimPos.z + offset.z});

			dirty = false;
			aimOldPos = {x: aimPos.x, y: aimPos.y, z: aimPos.z};
		};

		return sys;
	};

	return module;
});
